package com.dhcc.core.config;

import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

/**
 * ehcache配置
 * 
 * @ClassName: EhCacheConfig
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午9:41:59
 */
@Configuration
@EnableCaching
public class EhCacheConfig {

    /**
     * EhCacheFactoryBean的配置
     */
    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cacheManagerFactoryBean.setShared(true);
        return cacheManagerFactoryBean;
    }

    /**
     * EhCacheCacheManager的配置
     */
    @Bean
    public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean ehCacheManagerFactoryBean) {
        return new EhCacheCacheManager(ehCacheManagerFactoryBean.getObject()) {
            @Override
            protected Cache getMissingCache(String name) {
                Cache cache = super.getMissingCache(name);
                if (cache == null) {
                    //使用default配置克隆缓存
                    getCacheManager().addCacheIfAbsent(name);
                    cache = super.getCache(name);
                }
                return cache;
            }
        };
    }
    
    /**
     * shiro缓存管理器 使用Ehcache实现
     */
    @Bean
    public org.apache.shiro.cache.CacheManager cacheShiroManager(EhCacheManagerFactoryBean ehcache) {
        EhCacheManager ehCacheManager = new EhCacheManager();
        ehCacheManager.setCacheManager(ehcache.getObject());
        return ehCacheManager;
    }
}
